(function() {
    'use strict';
    
    // 基础配置参数
    const baseConfig = {
        gifUrl: 'https://www.sakuraidc.cc/JS/xp.gif',
        blowAwaySpeed: 15, // 吹飞速度
        blowAwayDuration: 1000, // 吹飞持续时间(毫秒)
        zIndex: 9999 // 层级
    };
    
    // 响应式配置 - 根据屏幕宽度调整参数
    const responsiveConfig = {
        mobile: { // 手机端 (< 768px)
            snowflakeCount: 8,
            minSpeed: 0.8,
            maxSpeed: 2,
            minSwing: 0.3,
            maxSwing: 1.5,
            minRotationSpeed: 0.3,
            maxRotationSpeed: 1.5,
            blowAwayRange: 100
        },
        tablet: { // 平板端 (768px - 1024px)
            snowflakeCount: 12,
            minSpeed: 1,
            maxSpeed: 2.5,
            minSwing: 0.4,
            maxSwing: 1.8,
            minRotationSpeed: 0.4,
            maxRotationSpeed: 1.8,
            blowAwayRange: 120
        },
        desktop: { // 桌面端 (> 1024px)
            snowflakeCount: 15,
            minSpeed: 1,
            maxSpeed: 3,
            minSwing: 0.5,
            maxSwing: 2,
            minRotationSpeed: 0.5,
            maxRotationSpeed: 2,
            blowAwayRange: 150
        },
        largeDesktop: { // 大屏桌面 (> 1440px)
            snowflakeCount: 20,
            minSpeed: 1.2,
            maxSpeed: 3.5,
            minSwing: 0.6,
            maxSwing: 2.2,
            minRotationSpeed: 0.6,
            maxRotationSpeed: 2.2,
            blowAwayRange: 180
        }
    };
    
    // 获取当前配置
    function getCurrentConfig() {
        const width = window.innerWidth;
        const height = window.innerHeight;
        const isPortrait = height > width;
        const screenSize = Math.max(width, height); // 使用较大的尺寸作为判断依据
        
        // 检测是否为移动设备
        const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
        
        let deviceConfig;
        
        if (isMobile) {
            // 移动设备：根据屏幕的最大尺寸判断
            if (screenSize < 768) {
                deviceConfig = responsiveConfig.mobile;
            } else if (screenSize < 1024) {
                deviceConfig = responsiveConfig.tablet;
            } else {
                deviceConfig = responsiveConfig.desktop;
            }
        } else {
            // 桌面设备：使用传统的宽度判断
            if (width < 768) {
                deviceConfig = responsiveConfig.mobile;
            } else if (width < 1024) {
                deviceConfig = responsiveConfig.tablet;
            } else if (width < 1440) {
                deviceConfig = responsiveConfig.desktop;
            } else {
                deviceConfig = responsiveConfig.largeDesktop;
            }
        }
        
        // 竖屏模式下的特殊调整
        if (isPortrait && isMobile) {
            // 竖屏时适当减少雪花数量，提高性能
            deviceConfig = { ...deviceConfig };
            deviceConfig.snowflakeCount = Math.max(Math.floor(deviceConfig.snowflakeCount * 0.8), 5);
            // 竖屏时减小吹飞范围，适应较窄的屏幕
            deviceConfig.blowAwayRange = Math.floor(deviceConfig.blowAwayRange * 0.8);
        }
        
        return { ...baseConfig, ...deviceConfig };
    }
    
    // 当前使用的配置
    let config = getCurrentConfig();
    
    // 雪花类
    class Snowflake {
        constructor() {
            this.element = document.createElement('img');
            this.element.src = config.gifUrl;
            this.element.style.position = 'fixed';
            this.element.style.pointerEvents = 'auto'; // 允许点击
            this.element.style.zIndex = config.zIndex;
            this.element.style.userSelect = 'none';
            this.element.style.cursor = 'pointer';
            this.element.style.opacity = '0'; // 初始隐藏，避免闪烁
            
            this.isBlownAway = false;
            this.blowStartTime = 0;
            this.blowDirection = { x: 0, y: 0 };
            this.isLoaded = false;
            
            this.reset(true); // 初始化时随机分布
            this.setupStyles();
            this.setupClickHandler();
            
            // 监听图片加载完成事件
            this.element.onload = () => {
                this.size = Math.max(this.element.naturalWidth, this.element.naturalHeight);
                // 只有当雪花在顶部上方时才调整位置（避免影响初始随机分布）
                if (this.y === -100) {
                    this.y = -this.size;
                }
                this.isLoaded = true;
                this.setupStyles(); // 重新设置样式，包括显示雪花
            };
            
            document.body.appendChild(this.element);
        }
        
        reset(isInitial = false) {
            // 使用图片原始大小，不进行调整
            this.size = null; // 将在图片加载后设置
            
            // 随机水平位置
            this.x = Math.random() * window.innerWidth;
            
            // 初始化时随机分布在整个屏幕，重置时从顶部开始
            if (isInitial) {
                this.y = Math.random() * window.innerHeight; // 初始化时随机分布
            } else {
                this.y = -100; // 重置时从顶部上方开始
            }
            
            // 随机下落速度
            this.speed = Math.random() * (config.maxSpeed - config.minSpeed) + config.minSpeed;
            
            // 随机摆动参数
            this.swingSpeed = Math.random() * 0.02 + 0.01;
            this.swingAmount = Math.random() * (config.maxSwing - config.minSwing) + config.minSwing;
            this.swingOffset = Math.random() * Math.PI * 2;
            
            // 随机旋转参数（包含随机方向）
            const baseRotationSpeed = Math.random() * (config.maxRotationSpeed - config.minRotationSpeed) + config.minRotationSpeed;
            // 随机选择旋转方向：50%概率顺时针，50%概率逆时针
            this.rotationSpeed = Math.random() < 0.5 ? baseRotationSpeed : -baseRotationSpeed;
            this.rotation = 0;
            
            // 透明度
            this.opacity = Math.random() * 0.6 + 0.4;
            
            // 重置吹飞状态
            this.isBlownAway = false;
            this.blowStartTime = 0;
        }
        
        setupStyles() {
            // 不设置宽高，保持图片原始尺寸
            this.element.style.opacity = this.isLoaded ? this.opacity : '0';
            this.element.style.left = this.x + 'px';
            this.element.style.top = this.y + 'px';
        }
        
        setupClickHandler() {
            this.element.addEventListener('click', (e) => {
                e.preventDefault();
                e.stopPropagation(); // 防止事件冒泡
                // 通知管理器处理范围吹飞
                if (this.manager) {
                    this.manager.blowAwayInRange(e.clientX, e.clientY);
                }
            });
        }
        
        blowAway(clickX, clickY) {
            if (this.isBlownAway) return;
            
            this.isBlownAway = true;
            this.blowStartTime = Date.now();
            
            // 计算吹飞方向（从点击位置向外）
            const centerX = this.x + (this.size || 50) / 2;
            const centerY = this.y + (this.size || 50) / 2;
            const deltaX = centerX - clickX;
            const deltaY = centerY - clickY;
            const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY) || 1;
            
            // 归一化方向向量并添加随机性
            this.blowDirection.x = (deltaX / distance) * config.blowAwaySpeed + (Math.random() - 0.5) * 5;
            this.blowDirection.y = (deltaY / distance) * config.blowAwaySpeed + (Math.random() - 0.5) * 5;
            
            // 增加旋转速度
            this.rotationSpeed *= 3;
        }
        
        update() {
            if (this.isBlownAway) {
                // 吹飞状态的更新逻辑
                const elapsed = Date.now() - this.blowStartTime;
                const progress = elapsed / config.blowAwayDuration;
                
                if (progress >= 1) {
                    // 吹飞动画结束，重置雪花
                    this.reset();
                    this.setupStyles();
                    return;
                }
                
                // 应用吹飞运动
                this.x += this.blowDirection.x;
                this.y += this.blowDirection.y;
                
                // 逐渐减少透明度
                this.opacity = (1 - progress) * (this.opacity || 0.8);
                
                // 更新旋转角度
                this.rotation += this.rotationSpeed;
                
                // 应用位置、旋转和透明度
                this.element.style.left = this.x + 'px';
                this.element.style.top = this.y + 'px';
                this.element.style.transform = `rotate(${this.rotation}deg)`;
                this.element.style.opacity = this.opacity;
                
            } else {
                // 正常飘落状态的更新逻辑
                // 更新垂直位置
                this.y += this.speed;
                
                // 更新水平摆动
                this.x += Math.sin(Date.now() * this.swingSpeed + this.swingOffset) * this.swingAmount;
                
                // 更新旋转角度
                this.rotation += this.rotationSpeed;
                
                // 应用位置和旋转
                this.element.style.left = this.x + 'px';
                this.element.style.top = this.y + 'px';
                this.element.style.transform = `rotate(${this.rotation}deg)`;
                
                // 如果雪花落到屏幕底部，重置位置
                const effectiveSize = this.size || 100; // 使用默认值防止未加载时的问题
                if (this.y > window.innerHeight + effectiveSize) {
                    this.reset();
                    this.setupStyles();
                }
                
                // 如果雪花飘出屏幕左右边界，调整位置
                if (this.x < -effectiveSize) {
                    this.x = window.innerWidth + effectiveSize;
                } else if (this.x > window.innerWidth + effectiveSize) {
                    this.x = -effectiveSize;
                }
            }
        }
        
        destroy() {
            if (this.element && this.element.parentNode) {
                this.element.parentNode.removeChild(this.element);
            }
        }
    }
    
    // 雪花管理器
    class SnowfallManager {
        constructor() {
            this.snowflakes = [];
            this.isRunning = false;
            this.animationId = null;
        }
        
        init() {
            // 等待DOM加载完成
            if (document.readyState === 'loading') {
                document.addEventListener('DOMContentLoaded', () => this.start());
            } else {
                this.start();
            }
            
            // 监听窗口大小变化
            window.addEventListener('resize', () => this.handleResize());
        }
        
        start() {
            if (this.isRunning) return;
            
            this.isRunning = true;
            
            // 创建雪花
            this.createSnowflakes();
            
            // 添加全局点击监听器
            this.setupGlobalClickHandler();
            
            // 开始动画循环
            this.animate();
        }
        
        createSnowflakes() {
            // 清除现有雪花
            this.snowflakes.forEach(snowflake => {
                if (snowflake.element && snowflake.element.parentNode) {
                    snowflake.element.parentNode.removeChild(snowflake.element);
                }
            });
            this.snowflakes = [];
            
            // 根据当前配置创建雪花
            for (let i = 0; i < config.snowflakeCount; i++) {
                const snowflake = new Snowflake();
                snowflake.manager = this; // 设置管理器引用
                this.snowflakes.push(snowflake);
            }
        }
        
        setupGlobalClickHandler() {
            // 移除之前的监听器（如果存在）
            if (this.globalClickHandler) {
                document.removeEventListener('click', this.globalClickHandler);
            }
            
            // 创建新的全局点击处理器
            this.globalClickHandler = (e) => {
                // 检查点击是否在雪花上，如果是则跳过（由雪花自己处理）
                if (e.target.tagName === 'IMG' && e.target.src.includes(config.gifUrl.split('/').pop())) {
                    return;
                }
                
                // 处理空白区域的点击
                this.blowAwayInRange(e.clientX, e.clientY);
            };
            
            // 添加全局点击监听器
            document.addEventListener('click', this.globalClickHandler);
        }
        
        animate() {
            if (!this.isRunning) return;
            
            // 更新所有雪花
            this.snowflakes.forEach(snowflake => snowflake.update());
            
            // 请求下一帧
            this.animationId = requestAnimationFrame(() => this.animate());
        }
        
        stop() {
            this.isRunning = false;
            
            if (this.animationId) {
                cancelAnimationFrame(this.animationId);
                this.animationId = null;
            }
            
            // 移除全局点击监听器
            if (this.globalClickHandler) {
                document.removeEventListener('click', this.globalClickHandler);
                this.globalClickHandler = null;
            }
            
            // 销毁所有雪花
            this.snowflakes.forEach(snowflake => snowflake.destroy());
            this.snowflakes = [];
            
            // 移除窗口大小变化监听器
            window.removeEventListener('resize', () => this.handleResize());
        }
        
        handleResize() {
            // 更新配置
            const newConfig = getCurrentConfig();
            const needRecreate = newConfig.snowflakeCount !== config.snowflakeCount;
            config = newConfig;
            
            if (needRecreate) {
                // 如果雪花数量发生变化，重新创建雪花
                this.createSnowflakes();
            } else {
                // 否则只调整现有雪花位置
                this.snowflakes.forEach(snowflake => {
                    const effectiveSize = snowflake.size || 100;
                    if (snowflake.x > window.innerWidth) {
                        snowflake.x = window.innerWidth - effectiveSize;
                    }
                });
            }
        }
        
        blowAwayInRange(clickX, clickY) {
            // 计算范围内的所有雪花并吹飞它们
            this.snowflakes.forEach(snowflake => {
                if (snowflake.isBlownAway) return;
                
                // 使用雪花的实际边界进行更精确的检测
                const snowflakeSize = snowflake.size || 50;
                const snowflakeLeft = snowflake.x;
                const snowflakeRight = snowflake.x + snowflakeSize;
                const snowflakeTop = snowflake.y;
                const snowflakeBottom = snowflake.y + snowflakeSize;
                
                // 计算点击位置到雪花边界的最短距离
                let distanceX = 0;
                let distanceY = 0;
                
                if (clickX < snowflakeLeft) {
                    distanceX = snowflakeLeft - clickX;
                } else if (clickX > snowflakeRight) {
                    distanceX = clickX - snowflakeRight;
                }
                
                if (clickY < snowflakeTop) {
                    distanceY = snowflakeTop - clickY;
                } else if (clickY > snowflakeBottom) {
                    distanceY = clickY - snowflakeBottom;
                }
                
                const distance = Math.sqrt(distanceX * distanceX + distanceY * distanceY);
                
                // 如果点击在雪花内部，距离为0，直接吹飞
                // 否则检查是否在吹飞范围内
                if (distance <= config.blowAwayRange) {
                    snowflake.blowAway(clickX, clickY);
                }
            });
        }
    }
    
    // 创建全局实例
    const snowfallManager = new SnowfallManager();
    
    // 暴露控制接口到全局
    window.SnowfallEffect = {
        start: () => snowfallManager.start(),
        stop: () => snowfallManager.stop(),
        config: config
    };
    
    // 自动初始化
    snowfallManager.init();
    
})();

// 使用说明：
// 1. 通过 <script src="snowfall.js"></script> 引入
// 2. 自动开始雪花效果
// 3. 可通过 SnowfallEffect.stop() 停止效果
// 4. 可通过 SnowfallEffect.start() 重新开始效果
// 5. 可通过 SnowfallEffect.config 修改配置参数